package label

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/framework/dao"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"gitee.com/bobo-rs/idea-space-framework/pkg/utils"
	"github.com/gogf/gf/v2/errors/gerror"
	"strconv"
)

// SaveLabelValues 保存标签值-批量或单条保存
func (l *sLabel) SaveLabelValues(ctx context.Context, in model.LabelValuesSaveInput) (out *model.LabelValuesSaveOutput, err error) {
	// 处理数据
	saveAll, err := l.processLabelValueSave(ctx, in)
	if err != nil {
		return nil, err
	}

	// 同步数据
	resp, err := dao.LabelValues.Ctx(ctx).Save(saveAll)
	if err != nil {
		return nil, err
	}
	// 插入失败
	valueId, err := resp.LastInsertId()
	if err != nil {
		return nil, gerror.Wrapf(err, `插入标签值失败：`, err.Error())
	}
	return &model.LabelValuesSaveOutput{
		Id: uint(valueId),
	}, nil
}

// processLabelValueSave 处理保存标签数据
func (l *sLabel) processLabelValueSave(ctx context.Context, in model.LabelValuesSaveInput) (saveAll []model.LabelValueSaveItem, err error) {
	var (
		values = utils.SeparatorStringToArray(in.Values)
		detail = model.LabelValueDetailItem{}
	)
	// 拆分标签值
	if len(values) == 0 {
		return nil, gerror.New(`标签值验证不存在`)
	}
	saveAll = []model.LabelValueSaveItem{}
	// 处理数据
	for _, value := range values {
		item := model.LabelValueSaveItem{
			LabelValueItem: model.LabelValueItem{
				LabelId: in.LabelId,
				Value:   value,
			},
			Hash: l.processLabelValueHash(in.LabelId, value),
		}
		// 获取详情信息
		err = l.ProcessLabelValueDetailByHash(ctx, item.Hash, &detail)
		if err == nil {
			item.Id = detail.Id
		}

		// 填充数据
		saveAll = append(saveAll, item)
	}
	return saveAll, nil
}

// processLabelValueHash 处理标签hash值
func (l *sLabel) processLabelValueHash(labelId uint, value string) string {
	return utils.HashMd5String(strconv.Itoa(int(labelId)), value)
}
